import random
import time
import pygame
from core import Core
from constants import Constants
from game_state import GameState
from game_data import GameData


class GameLogic:
    """处理游戏逻辑的类"""

    def __init__(self, game_data: GameData, game_state: GameState,):
        self.game_data = game_data
        self.game_state = game_state
        self.core = Core(game_data)
        self.ui_components = None
        self.resources = None

    def print_character_data(self):
        print("Index | Model       | Name           | Bullet Position | Current Position")
        print("------|-------------|----------------|-----------------|-----------------")

        for i, char_data in enumerate(self.game_data.character_data_game):
            print(
                f"{i:5} | {char_data['model']:15} | {char_data['name']:14} | "
                f"{char_data['bullet_position_game']:15} | {char_data['current_position']:15}"
            )

    def validate_game_settings(self):
        # 检查模型是否唯一
        selected_models = [data["model"] for data in self.game_data.character_data_init]
        if len(set(selected_models)) != len(selected_models):
            self.game_state.error_message = "错误：四个角色的模型必须各不相同！"
            self.game_state.error_message_time = time.time()
            return False

        # 检查弹夹容量和子弹位置
        for i, data in enumerate(self.game_data.character_data_init):
            try:
                clip_capacity = int(self.game_data.input_values[i])
                bullet_position_init = int(self.game_data.input_values[i + 4])
            except ValueError:
                self.game_state.error_message = f"错误：{data['name']}的弹夹容量或子弹位置不能为空！"
                self.game_state.error_message_time = time.time()
                return False

            if clip_capacity <= 0:
                self.game_state.error_message = f"错误：{data['name']}的弹夹容量必须大于0！"
                self.game_state.error_message_time = time.time()
                return False

            if bullet_position_init <= 0:
                self.game_state.error_message = f"错误：{data['name']}的子弹位置必须大于0！"
                self.game_state.error_message_time = time.time()
                return False

            if clip_capacity > 6:
                self.game_state.error_message = f"错误：{data['name']}的弹夹容量不能超过6！"
                self.game_state.error_message_time = time.time()
                return False

            if bullet_position_init > clip_capacity:
                self.game_state.error_message = f"错误：{data['name']}的子弹位置不能超过弹夹容量！"
                self.game_state.error_message_time = time.time()
                return False

        return True

    def randomize_character_data(self):
        """随机生成角色信息"""
        random_models = random.sample(self.game_data.models_init, len(self.game_data.models_init))
        for i, data in enumerate(self.game_data.character_data_init):
            data["model"] = random_models[i]
            data["clip_capacity"] = random.randint(1, 6)
            data["bullet_position_init"] = random.randint(1, data["clip_capacity"])
            self.game_data.input_values[i] = str(data["clip_capacity"])
            self.game_data.input_values[i + 4] = str(data["bullet_position_init"])

    def handle_init_screen_click(self, event_pos):
        """处理初始化界面的点击事件"""
        # 检测按钮点击
        if self.ui_components.button_random.collidepoint(event_pos):
            self.randomize_character_data()
        elif self.ui_components.button_play.collidepoint(event_pos):
            # 首先更新角色数据
            for i in range(4):
                try:
                    self.game_data.character_data_init[i]["clip_capacity"] = int(self.game_data.input_values[i])
                    self.game_data.character_data_init[i]["bullet_position_init"] = int(
                        self.game_data.input_values[i + 4])
                except ValueError:
                    self.game_data.character_data_init[i]["clip_capacity"] = 0
                    self.game_data.character_data_init[i]["bullet_position_init"] = 0
                    pass

            for i in range(4):
                # 复制所有需要的数据
                self.game_data.character_data_game[i] = {
                    "name": self.game_data.character_data_init[i]["name"],
                    "model": self.game_data.character_data_init[i]["model"],
                    "bullet_position_game": self.game_data.character_data_init[i]["bullet_position_init"],
                    "current_position": 0,
                    "clip_capacity": self.game_data.character_data_init[i]["clip_capacity"]
                }

            if self.validate_game_settings():
                # self.print_character_data()
                self.game_state.current_screen = "game"

        # 检测名字点击
        for i, pos in enumerate(self.game_data.avatar_positions_one):
            name_rect = pygame.Rect(pos[0], pos[1] + 110, 100, 30)
            if name_rect.collidepoint(event_pos):
                next_index = (i + 1) % len(self.game_data.character_data_init)
                # 仅交换名字和头像
                self.game_data.character_data_init[i]["name"], self.game_data.character_data_init[next_index]["name"] = \
                    self.game_data.character_data_init[next_index]["name"], self.game_data.character_data_init[i][
                        "name"]
                self.resources.avatars[i], self.resources.avatars[next_index] = \
                    self.resources.avatars[next_index], self.resources.avatars[i]

        # 检测模型下拉框点击
        for i, dropdown_rect in enumerate(self.game_data.dropdown_rects):
            if dropdown_rect.collidepoint(event_pos):
                if self.game_state.dropdown_active == i:
                    self.game_state.dropdown_active = None
                else:
                    self.game_state.dropdown_active = i
            elif self.game_state.dropdown_active == i:
                for j, model in enumerate(self.game_data.models_init):
                    option_rect = pygame.Rect(dropdown_rect.x, dropdown_rect.y + (j + 1) * 30,
                                              dropdown_rect.width, 30)
                    if option_rect.collidepoint(event_pos):
                        self.game_data.character_data_init[i]["model"] = model
                        self.game_state.dropdown_active = None

        # 检测输入框点击
        for i, pos in enumerate(self.game_data.avatar_positions_one):
            input_y = pos[1] + 170
            if self.game_state.dropdown_active == i:
                input_y += len(self.game_data.models_init) * 30
            clip_label_x = self.game_data.avatar_positions_one[i][0]
            clip_text_x = clip_label_x + self.resources.font.size("弹夹容量")[0] + 5
            bullet_label_x = self.game_data.avatar_positions_one[i][0]
            bullet_y = input_y + 40
            bullet_text_x = bullet_label_x + self.resources.font.size("子弹位置")[0] + 5
            clip_text_rect = pygame.Rect(clip_text_x, input_y,
                                         self.resources.font.size(self.game_data.input_values[i])[0], 30)
            bullet_text_rect = pygame.Rect(bullet_text_x, bullet_y,
                                           self.resources.font.size(self.game_data.input_values[i + 4])[0], 30)
            if clip_text_rect.collidepoint(event_pos):
                self.game_state.input_active = i
            elif bullet_text_rect.collidepoint(event_pos):
                self.game_state.input_active = i + 4